import { defineStore } from "pinia";
import type { MenuTpye } from "#/user";
import { store } from "@/store/index";
interface UserState {
  menus: MenuTpye[];
}

export const useUserStore = defineStore("user", {
  state(): UserState {
    return {
      menus: [],
    };
  },
  getters: {
    genMenuConf(state) {
      const newMenus: Indexable<MenuTpye> = {};
      state.menus.forEach((menu) => {
        if (menu.parentId === 0) {
          // 一级权限对象
          newMenus[menu.id] = {
            ...menu,
            children: newMenus[menu.id]?.children,
          }; //一级对象的id与二级对象的parentId一致,将一级对象的id作为索引值
        } else {
          // 二级权限对象
          menu.parentId; //对应一级id
          newMenus[menu.parentId] ??= {} as MenuTpye;
          newMenus[menu.parentId].children ??= [];
          newMenus[menu.parentId].children!.push(menu);
        }
      });
      return newMenus;
    },
  },
  actions: {
    updateMenus(menus: MenuTpye[]) {
      this.menus = menus;
    },
  },
});

export const useUserStoreWithOut = () => useUserStore(store);
